﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using evt;
using info;
using tools;

public class UserView : MonoBehaviour {

	// Use this for initialization
	private Image HeadImg = null;
	private Text UserName = null;
	private Text UserID = null;
	private Text Diamonds = null;
	private WWW www = null;
	void Start () {

		HeadImg = transform.GetChild (1).GetChild (0).GetChild (0).GetComponent<Image> ();
		UserName = transform.GetChild (2).GetComponent<Text> ();
		UserID = transform.GetChild (3).GetComponent<Text> ();
		Diamonds = transform.GetChild (6).GetComponent<Text> ();
		transform.GetChild (5).GetComponent<Button> ().onClick.AddListener (RechargeView);
		EventTriggerListener.Get (HeadImg.gameObject).onClick = ClickHeadImg;

		if (info.UserInfo.headImg == null) {
			string headUrl = info.UserInfo.headUrl;
			headUrl = headUrl.Substring (0, headUrl.IndexOf ("/0")+2);
			www = new WWW (headUrl);
		} else {
			UserView.setHeadImg (HeadImg, info.UserInfo.headImg);
		}

	}

	public static void setHeadImg(Image img,Texture2D texture,int width=0,int height=0){
		Sprite pic = Sprite.Create(texture, new Rect(width, height, texture.width, texture.height), new Vector2(0.5f, 0.5f));
		img.sprite = pic;
	}

	public void TestSound (string value){
		SoundPlayer.play ("7571");
	}

	private void ClickHeadImg(GameObject go){
		evt.ServerEventDispather.getInstance ().Add(evt.ServerEvent.SHOW_MAIN_DETAIL,HeadImg.sprite);
		SoundPlayer.play ("7571");
	}

	private void RechargeView(){
		SoundPlayer.play ("7571");
		ServerEventDispather.getInstance ().Add (ServerEvent.ERROR_MSG, "支付平台待开发中");
		return;
		ServerEventDispather.getInstance ().Add (ServerEvent.OPEN_RECHARGE_VIEW, null);
	}
	
	// Update is called once per frame
	void Update () {
		
				if (UserInfo.UserData != null) {
					UserName.text = UserInfo.UserData.nickName;
					UserID.text = UserInfo.UserData.id.ToString();					
					Diamonds.text = UserInfo.UserData.diamond.ToString();
				}

		if(www != null){
			if(www.isDone){
				UserInfo.headImg = www.texture;
				UserView.setHeadImg (HeadImg, www.texture);
				www = null;
			}
		}
		
	}
}
